<?php


/**
 * Truncate a UTF-8-encoded string safely to a number of bytes.
 *
 * If the end position is in the middle of a UTF-8 sequence, it scans backwards
 * until the beginning of the byte sequence.
 *
 * Use this function whenever you want to chop off a string at an unsure
 * location. On the other hand, if you're sure that you're splitting on a
 * character boundary (e.g. after using strpos() or similar), you can safely use
 * substr() instead.
 *
 * @param $string
 *   The string to truncate.
 * @param $len
 *   An upper limit on the returned string length.
 * @param $wordsafe
 *   Flag to truncate at nearest space. Defaults to FALSE.
 * @return
 *   The truncated string.
 */
function truncate_utf8($string, $len, $wordsafe = FALSE, $dots = FALSE) {
  $slen = strlen($string);
  if ($slen <= $len) {
    return $string;
  }
  if ($wordsafe) {
    $end = $len;
    while (($string[--$len] != ' ') && ($len > 0)) {};
    if ($len == 0) {
      $len = $end;
    }
  }
  if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) {
    return substr($string, 0, $len) . ($dots ? ' ...' : '');
  }
  while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0) {};
  return substr($string, 0, $len) . ($dots ? ' ...' : '');
}

/**
 * Encode special characters in a plain-text string for display as HTML.
 */
function check_plain($text) {
  return htmlspecialchars($text, ENT_QUOTES);
}


function get_time_description($t)
	{
		$last_update="";
		$d=floor((time()-$t)/86400);
		if ($d<1)
		{
			$d_h=floor((time()-$t)/3600);
			if ($d_h<1)
			{
				$d_m=floor((time()-$t)/60);
				if ($d_m<1)
				{
					$d_s=time()-$t;
					$last_update="$d_s giây trước";
				}
				else
				{
					$last_update="$d_m phút trước";
				}
			}
			else if ($d_h<20)
			{
				$last_update="$d_h giờ trước";
			}
			else
			{
				$last_update="hôm nay";
			}
		}
		else if ($d<2)
		{
			$last_update="hôm qua";
		}
		else if ($d<10)
		{
			$last_update="$d ngày trước";
		}
		else
		{
			$last_update=date("d/m/Y", $t);
		}
		return $last_update;
	}

function video_get_short_title($title, $len=30)
{
	return truncate_utf8(wordwrap($title, 10, " ", TRUE), $len, TRUE, TRUE);
}


function _utils_get_smilley_list()
{
	static $smilley=null;
	static $smilley_key=null;
	static $smilley_token=null;
	static $emotions=null;
	if ($smilley==null)
	{
		$smilley = array(	':)'=>'{_smile_}',
							':('=>'{_sad_}',
							';)'=>'{_winking_}',
							':D'=>'{_big_grin_}',
							';;)'=>'{_batting_eyelashes_}',
							'>:D<'=>'{_big_hug_}',
							':-/'=>'{_confused_}',
							':x'=>'{_love_struck_}',
							':">'=>'{_blushing_}',
							':P'=>'{_tongue_}',
							':*'=>'{_kiss_}',
							'=(('=>'{_broken_heart_}',
							':o'=>'{_surprise_}',
							':X'=>'{_angry_}',
							':>'=>'{_smug_}',
							'B-)'=>'{_cool_}',
							':-S'=>'{_worried_}',
							'#:-S'=>'{_whew_}',
							'>:)'=>'{_devil_}',
							':(('=>'{_crying_}',
							':))'=>'{_laughing_}',
							':|'=>'{_straight_face_}',
							'/:)'=>'{_raised_eyebrow_}',
							'=))'=>'{_rolling_on_the_floor_}',
							'O:)'=>'{_angel_}',
							':-B'=>'{_nerd_}',
							'=;'=>'{_talk_to_the_hand_}',
							'l-|'=>'{_sleepy_}',
							'8-|'=>'{_rolling_eyes_}',
							'L-)'=>'{_loser_}',
							':-&'=>'{_sick_}',
							':-$'=>'_dont_tell_anyone_}',
							'[-)'=>'{_not_talking_}',
							':o)'=>'{_clown_}',
							'8-}'=>'{_silly_}',
							'<:-P'=>'{_party_}',
							'(:|'=>'{_yawn_}',
							'=P~'=>'{_drooling_}',
							':-?'=>'{_thinking_}',
							'#-o'=>'{_doh_}',
							'=D>'=>'{_applause_}',
							':-SS'=>'{_nailbiting_}',
							'@-)'=>'{_hypnotized_}',
							':^)'=>'{_liar_}',
							':-w'=>'{_waiting_}',
							':-<'=>'_{sigh_}',
							'>:p'=>'{_phbbbbt_}'/*,
							':-j'=>'{_oh_go_on_}',
							':@)'=>'{_pig_}',
							'3:-O'=>'{_cow_}',
							':(|)'=>'{_monkey_}',
							'~:>'=>'{_chicken_}',
							':-"'=>	'{_whistling_}',
							'b-('=>'{_feeling_beat_up_}',
							'\:D/'=>'{_dancing_}',
							';))'=>'{_hee_hee_}',
							'^:)^'=>'{_not_worthy_}',*/);
							
		$smilley_key=array_keys($smilley);
		$smilley_token=array_values($smilley);
		$emotions=array();
		for ($i=0; $i<count($smilley_token); $i++)
		{
			$emotions[]='<img src="http://img.tamtay.vn/misc/smilley/' . ($i+1) . '.gif" align="absmiddle" />';
		}
		
		//short
		for ($i=0; $i<(count($smilley_key)-1); $i++)
		{
			$max_length=$i;
			for ($j=$i+1; $j<count($smilley_key); $j++)
			{
				if (strlen($smilley_key[$max_length]) < strlen($smilley_key[$j]))
				{
					$max_length=$j;
				}
			}
			if ($max_length>$i)
			{
				$temp=$smilley_key[$i];
				$smilley_key[$i]=$smilley_key[$max_length];
				$smilley_key[$max_length]=$temp;
				
				$temp=$smilley_token[$i];
				$smilley_token[$i]=$smilley_token[$max_length];
				$smilley_token[$max_length]=$temp;
				
				$temp=$emotions[$i];
				$emotions[$i]=$emotions[$max_length];
				$emotions[$max_length]=$temp;
			}
		}
	}
	
	return array($smilley_key, $smilley_token, $emotions);
}

function _utils_comment_parse_emotion($message)
{
	list($smilley_key, $smilley_token, $emotions)=_utils_get_smilley_list();
	//print_r($emotions);
	$message=stripcslashes($message);
	//change emotion to tocken (prevent check_plain replace speacial chars)
	$message = str_replace($smilley_key, $smilley_token, $message);
	//replace special char
	$message=nl2br(check_plain($message));
	//replace tocken with emotion
	$message = str_replace($smilley_token, $emotions, $message);
	return $message;
}


 	/**
    *
    * Convert an object to an array
    *
    * @param    object  $object The object to convert
    * @reeturn      array
    *
    */
    function objectToArray( $object )
    {
        if( !is_object( $object ) && !is_array( $object ) )
        {
            return $object;
        }
        if( is_object( $object ) )
        {
            $object = get_object_vars( $object );
        }
        return array_map( 'objectToArray', $object );
    }
    
    
    function eventImageNormalizeFilename($file_name)
	{
		$special_chars = array ("#", "$", "%", "^", "&", "*", "!", "~", "�", "\"", "�", "'", "=", "?", "/", "[", "]", "(", ")", "|", "<", ">", ";", "\\", ",");
	    $file_name = str_replace($special_chars, "", $file_name);  // remove special characters
	    return $file_name;
	}
	
	
	function videoGetSecureTocken($vid, $t)
	{
		if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) 
			$remote_host = $_SERVER["HTTP_X_FORWARDED_FOR"];
		else 
			$remote_host = $_SERVER["REMOTE_ADDR"];
	
		$sec="tamtay_video_123456788";
		return md5($t . $sec . $vid . $remote_host);
	}
	
	
// Composite two object
function composite_object($objA, $objB, $changeArr=array('like_count'=>'vote_web_count')){
	if($objA && is_object($objA)){
		if($objB && is_object($objB)){
			$objB = (array)$objB;
			if(count($objB) > 0){
				foreach($objB as $key=>$value){
					$objA->$key = $value;
				}
			}
		}
		if(is_array($changeArr)&& count($changeArr)>0){
			foreach($changeArr as $old=>$new){
				if($new != '' && $old!= '' && !isset($objA->$new))
					$objA->$new = $objA->$old;
			}
		}
		return $objA;
	}
	else{
		if($objB && is_object($objB)){
			if(is_array($changeArr)&& count($changeArr)>0){
				foreach($changeArr as $old=>$new){
					if($new != '' && $old!= '' && !isset($objB->$new))
						$objB->$new = $objB->$old;
				}
			}
			return $objB;
		}
		else{
			return (object)$objB;
		}
	}
	
}

// search a object in $arr and merge with $obj by $idname
// @param: $has: $arr has the object associate with $obj
function searchAndMergeObject($obj, $arr, $idnameArr, $changeArr=array('like_count'=>'vote_web_count'), $has=true){
	
	if(is_array($arr) && count($arr) >0 && is_array($idnameArr) && count($idnameArr)>0){
		
		foreach($arr as $item){
			$equal = true;
			
			foreach($idnameArr as $master=>$slave){
				
				if($obj->$master != $item->$slave){
					$equal = false;
					break;
				}
			}
			if($equal){
				
				return @composite_object($item, $obj, $changeArr);
			}
		}
		if($has)
			return false;
	}
	else if($has)
		return false;
	return $obj;
}

function double_vote_cmp(&$vObj1, &$vObj2)
{
	global $total_vote_web, $total_vote_sms; 
	// Calculate total vote
	if(!isset($vObj1->t) || !$vObj1->t){
		$web_vote = $vObj1->vote_web_count;
		if ($total_vote_web==0){
			$web_percent=0;
		}
		else{
			$web_percent=round($web_vote/$total_vote_web, 4)*100;
		}
		if ($total_vote_sms==0){
			$sms_percent=0;
		}
		else{
			$sms_percent=round($vObj1->vote_sms_count/$total_vote_sms, 4)*100;
		}
		$vObj1->t=$web_percent + $sms_percent;
	}
	if(!isset($vObj2->t) || !$vObj2->t){
		$web_vote = $vObj2->vote_web_count;
		if ($total_vote_web==0){
			$web_percent=0;
		}
		else{
			$web_percent=round($web_vote/$total_vote_web, 4)*100;
		}
		if ($total_vote_sms==0){
			$sms_percent=0;
		}
		else{
			$sms_percent=round($vObj2->vote_sms_count/$total_vote_sms, 4)*100;
		}
		$vObj2->t=$web_percent + $sms_percent;
	}
    if ($vObj1->t == $vObj2->t) {
        return 0;
    }
    return ($vObj1->t > $vObj2->t) ? -1 : 1;
}
	
class ttFormatText{
	private static $disalowedtags = array("script",
                        "object",
                        "iframe",
                        "image",
                        "applet",
                        "meta",
                        "form",
                        "onmouseover",
                        "onmouseout");
	static function stripTags($text, $tags = array()){
		$args = func_get_args();
        $text = array_shift($args);
        $tags = func_num_args() > 2 ? array_diff($args,array($text))  : (array)$tags;
        if(count($tags) <= 0)
        	$tags = ttFormatText::$disalowedtags;
        foreach ($tags as $tag){
            if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){
                $text = str_replace($found[0],$found[1],$text);
          }
        }

        return $text;
	}
}


class ttCheckInput{
	static function checkEmail($email){
		$pattern = '/^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/i';
		if(preg_match($pattern, $email))
			return true;
		else
			return false;
	}
	
	static function checkWebsite($url){
		//$pattern = "/^(https?|ftp)\:\/\/([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*(\:[0-9]{2,5})?(\/([a-z0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?\$/i";
		//"'|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i'"
		$pattern = '|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i';
		if(preg_match($pattern, $url))
			return true;
		else
			return false;
	}
	
	static function checkUsername($username){
		return true;
	}
	
	static function checkShortCut($short_cut){
		return true;
	}
}

